import { Router, Request, Response } from "express";
import { UserController } from "../Database/controller/UserController";

type Controller = typeof UserController;

type RoutesArray = {
    method: "get" | "post" | "delete" | "put";
    route: string;
    controller: Controller;
    action: string;
}[];

export const Routes: RoutesArray = [{
    method: "get",
    route: "/",
    controller: UserController,
    action: "all"
}, {
    method: "get",
    route: "/:id",
    controller: UserController,
    action: "one"
}, {
    method: "post",
    route: "/",
    controller: UserController,
    action: "save"
}, {
    method: "delete",
    route: "/:id",
    controller: UserController,
    action: "remove"
}];

export async function createRouter(): Promise<Router> {
    const router = Router();
    Routes.map((value) => {
        const { method, route, controller, action } = value;
        router[method](route, (req: Request, res: Response, next: Function) => {
            const result = (new (controller as any))[action](req, res, next);
            if (result instanceof Promise) {
                result.then(result => result !== null && result !== undefined ? res.send(result) : undefined);
            } else if (result !== null && result !== undefined) {
                res.json(result);
            }
        })
    });
    return router;
}
